package com.city.api;

import com.city.config.Code;
import com.city.domain.pub.PubUser;
import com.city.domain.report.CtUser;
import com.city.helper.AuthHelper;
import com.city.repository.report.CtUserRepository;
import com.city.service.report.AuthService;
import com.city.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 雷楚桥
 * @deprecation 权限认证api
 * @email leichuqiao@126.com
 * @date 2018/7/21 13:08
 */
@RestController
@RequestMapping("/api/auth")
public class AuthApi {
    @Autowired
    private AuthHelper authH;
    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private AuthService authS;
    @Autowired
    private CtUserRepository ctUserRepository;

    /**
     * @deprecation 获取二维码
     * @author 雷楚桥
     * @date 2018/7/21 13:08
     */
    @RequestMapping(value = "/getImage")
    public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 存入会话session
        HttpSession session = request.getSession(true);
        // 删除以前的
        session.removeAttribute("verCode");
        session.removeAttribute("codeTime");
        session.setAttribute("verCode", verifyCode.toLowerCase());
        session.setAttribute("codeTime", LocalDateTime.now());
        // 生成图片
        int w = 100, h = 30;
        OutputStream out = response.getOutputStream();
        VerifyCodeUtils.outputImage(w, h, out, verifyCode);
    }

    /**
     * @deprecation 验证码认证
     * @author 雷楚桥
     * @date 2018/7/21 13:09
     */
    @RequestMapping(value = "/validImage")
    public String validImage(HttpServletRequest request, HttpSession session) {
        String code = request.getParameter("code");
        Object verCode = session.getAttribute("verCode");
        if (null == verCode) {
            request.setAttribute("errmsg", "验证码已失效，请重新输入");
            return "验证码已失效，请重新输入";
        }
        String verCodeStr = verCode.toString();
        LocalDateTime localDateTime = (LocalDateTime) session.getAttribute("codeTime");
        long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)) {
            request.setAttribute("errmsg", "验证码错误");
            return "验证码错误";
        } else if ((now - past) / 1000 / 60 > 5) {
            request.setAttribute("errmsg", "验证码已过期，重新获取");
            return "验证码已过期，重新获取";
        } else {
            //验证成功，删除存储的验证码
            session.removeAttribute("verCode");
            return "200";
        }
    }


    /**
     * @deprecation 发送随机码
     * @params tel String 电话号码
     * @author 雷楚桥
     * @date 2018/7/21 14:40
     */
    @ResponseBody
    @PostMapping("/send")
    public String send(@Param("tel") String tel,
                       HttpSession session) {

        Long checkCodeTime = (Long) session.getAttribute("checkCodeTime");
        Long nowTime = System.currentTimeMillis();
        if (checkCodeTime != null && (nowTime - checkCodeTime) < 240000) {
            return "【短信校验码是:" + session.getAttribute("checkCode") +"】<br/>操作频率太快，请在&nbsp;" + (240000 - (nowTime - checkCodeTime)) / 1000 + "&nbsp;秒后再尝试";
        }

        String checkCode = CheckCodeUtils.getCheckCode(6);

        //测试代码块
        {
            session.setAttribute("loginTel", tel);
            session.setAttribute("checkCode", checkCode);
            session.setAttribute("checkCodeTime", System.currentTimeMillis());
            return "模拟短信发送，校验码是：" + checkCode;
        }

//        if (SMSHelper.send(tel, checkCode)) {
//            session.setAttribute("loginTel", tel);
//            session.setAttribute("checkCode", checkCode);
//            session.setAttribute("checkCodeTime", System.currentTimeMillis());
//            return "200";
//        }
//
//        return "发送短信失败";
    }

    /**
     * @deprecation 检验短信校验码是否正确
     * @params check String 校验码
     * @author 雷楚桥
     * @date 2018/7/21 19:24
     */
    @ResponseBody
    @PostMapping("/checkCode")
    public Map<String,Object> checkCode(@Param("checkCode") String checkCode,
                        @Param("tel") String tel,
                        HttpSession session){
        Map<String,Object> map = new HashMap<>();
        Long checkCodeTime = (Long)session.getAttribute("checkCodeTime");
        String code = (String)session.getAttribute("checkCode");
        Long nowTime = System.currentTimeMillis();
        String loginTel = (String)session.getAttribute("loginTel");
//        if(checkCodeTime == null || checkCode == null) {
//            map.put("code", Code.SEND_ERROR);
//            map.put("msg", "请先发送短信！");
//        }
//        if(nowTime - checkCodeTime > 300000){
//            session.setAttribute("checkCode",null);
//            session.setAttribute("checkCodeTime",null);
//            session.setAttribute("loginTel",null);
//
//            map.put("code", Code.CODE_EXPIRE);
//            map.put("msg", "校验码已过期，请重新发送校验码！");
//        }else if(!checkCode.equals(code)){
//            map.put("code", Code.CODE_ERROR);
//            map.put("msg", "校验码错误！");
//        }else{
            //检验码成功
            session.setAttribute("checkCode",null);
            session.setAttribute("checkCodeTime",null);

            //获取用户登录信息
            map = checkInfo(tel,checkCode,session);
//        }
        return map;
    }

    /**
     * @deprecation 获取用户登录信息
     * @params loginTel String 登录号码
     * @params session HttpSession 登录会话
     * @return String
     * @author 雷楚桥
     * @date 2018/7/22 14:04
     */
    private Map<String,Object> checkInfo(String tel,String checkCode,HttpSession session){
        Map<String,Object> map = new HashMap<>();
//        PubUser user = authS.findUserByLoginTel(loginTel);
        CtUser user = ctUserRepository.findByNameAndPassword(tel,checkCode);
        if(null == user){
            session.setAttribute("loginTel",null);
            map.put("code", Code.ACCOUNT_NOT_FIND);
            map.put("msg","对不起，账号不存在");
        }else{
            String sign = authH.updateSign(user.getId());
            Map<String,Object> data = new HashMap<>();

            session.setAttribute("laowangUser",user);
            data.put("sign",sign);

            map.put("code", Code.SUCCESS);
            map.put("data",data);
            map.put("msg","登录成功！");
        }
        return map;
    }
}
